// 高德地图工具函数
import type { AMapConfig, MapOptions, DistrictConfig } from './types'

// 高德地图API加载状态
let isAMapLoaded = false
let loadingPromise: Promise<void> | null = null

/**
 * 动态加载高德地图API
 * @param config 地图配置
 * @returns Promise
 */
export function loadAMapAPI(config: AMapConfig): Promise<void> {
  if (isAMapLoaded) {
    return Promise.resolve()
  }

  if (loadingPromise) {
    return loadingPromise
  }

  loadingPromise = new Promise((resolve, reject) => {
    // 检查是否已经加载
    if (window.AMap) {
      isAMapLoaded = true
      resolve()
      return
    }

    // 创建script标签
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.async = true
    
    // 构建API URL
    const plugins = config.plugins ? config.plugins.join(',') : ''
    script.src = `https://webapi.amap.com/maps?v=${config.version}&key=${config.key}${plugins ? `&plugin=${plugins}` : ''}`
    
    script.onload = () => {
      isAMapLoaded = true
      resolve()
    }
    
    script.onerror = () => {
      reject(new Error('高德地图API加载失败'))
    }
    
    document.head.appendChild(script)
  })

  return loadingPromise
}

/**
 * 创建地图实例
 * @param options 地图选项
 * @returns 地图实例
 */
export function createMap(options: MapOptions): any {
  if (!window.AMap) {
    throw new Error('高德地图API未加载')
  }

  const defaultOptions = {
    zoom: 10,
    center: [116.397428, 39.90923], // 北京
    mapStyle: 'amap://styles/normal',
    viewMode: '2D' as const,
    features: ['bg', 'road', 'building', 'point']
  }

  const mapOptions = { ...defaultOptions, ...options }
  return new window.AMap.Map(mapOptions.container, mapOptions)
}

/**
 * 创建行政区搜索实例
 * @param config 行政区配置
 * @returns Promise<行政区搜索实例>
 */
export function createDistrictSearch(config: DistrictConfig): Promise<any> {
  return new Promise((resolve, reject) => {
    if (!window.AMap) {
      reject(new Error('高德地图API未加载'))
      return
    }

    const districtSearch = new window.AMap.DistrictSearch({
      level: config.level,
      subdistrict: config.subdistrict || 1,
      extensions: config.extensions || 'all'
    })

    resolve(districtSearch)
  })
}

/**
 * 搜索行政区域
 * @param districtSearch 行政区搜索实例
 * @param keyword 关键词
 * @returns Promise<行政区数据>
 */
export function searchDistrict(districtSearch: any, keyword: string): Promise<any> {
  return new Promise((resolve, reject) => {
    districtSearch.search(keyword, (status: string, result: any) => {
      if (status === 'complete') {
        resolve(result)
      } else {
        reject(new Error(`行政区搜索失败: ${status}`))
      }
    })
  })
}

/**
 * 创建多边形覆盖物
 * @param map 地图实例
 * @param path 路径坐标
 * @param style 样式配置
 * @returns 多边形实例
 */
export function createPolygon(map: any, path: any[], style: any = {}): any {
  if (!window.AMap) {
    throw new Error('高德地图API未加载')
  }

  const defaultStyle = {
    strokeColor: '#0078ff',
    strokeWeight: 2,
    strokeOpacity: 1,
    fillColor: '#0078ff',
    fillOpacity: 0.3,
    strokeStyle: 'solid'
  }

  const polygonStyle = { ...defaultStyle, ...style }
  
  const polygon = new window.AMap.Polygon({
    path: path,
    ...polygonStyle
  })

  polygon.setMap(map)
  return polygon
}

/**
 * 清除地图上的覆盖物
 * @param map 地图实例
 * @param overlays 覆盖物数组
 */
export function clearOverlays(map: any, overlays: any[]): void {
  overlays.forEach(overlay => {
    if (overlay && overlay.setMap) {
      overlay.setMap(null)
    }
  })
  overlays.length = 0
}

/**
 * 设置地图视野以包含所有覆盖物
 * @param map 地图实例
 * @param overlays 覆盖物数组
 */
export function fitView(map: any, overlays: any[]): void {
  if (overlays.length > 0) {
    map.setFitView(overlays)
  }
}

/**
 * 获取区域中心点
 * @param boundaries 边界坐标数组
 * @returns 中心点坐标
 */
export function getDistrictCenter(boundaries: number[][][]): [number, number] {
  if (!boundaries || boundaries.length === 0) {
    return [116.397428, 39.90923] // 默认北京
  }

  let totalLng = 0
  let totalLat = 0
  let pointCount = 0

  boundaries.forEach(boundary => {
    boundary.forEach(point => {
      totalLng += point[0]
      totalLat += point[1]
      pointCount++
    })
  })

  return [totalLng / pointCount, totalLat / pointCount]
}

/**
 * 格式化行政区数据
 * @param districtData 原始行政区数据
 * @returns 格式化后的数据
 */
export function formatDistrictData(districtData: any): any {
  return {
    adcode: districtData.adcode,
    name: districtData.name,
    level: districtData.level,
    center: districtData.center,
    boundaries: districtData.boundaries,
    children: districtData.districtList || []
  }
}

// 声明全局AMap类型
declare global {
  interface Window {
    AMap: any
  }
}